const {
    sellersModel,
} = require("./models/sellersModel");

const mongoose = require("mongoose");
const { customersModel } = require('./models/customersModels');
const { ordersModel } = require("./models/ordersModels");
const { claimsModel } = require("./models/claimsModel");

module.exports.loginSellers = async params => {
    return await sellersModel.find({ account: params.sellersAccount, delete: false })
}

module.exports.addSellers = async function (params) {
    const data = await sellersModel.create(params)
    return data
}

module.exports.isExist = async function (params) {
    const data = await sellersModel.find(params)
    return data
}

module.exports.getAllSellers = async function (params) {
    return await sellersModel.find(params)
}

module.exports.getSellers = async function ({
    value,
    pageSize,
    currentPage
}) {
    const data = await sellersModel.aggregate([
        {
            $lookup: {
                // 设置关联的集合名称
                from: "customers",
                // 当前集合中做关联的属性名（字段）
                localField: "_id",
                // 被关联集合对应的属性名
                foreignField: "salesmansId",
                as: "customers"
            },
        },
        {
            $match: {
                delete: false,
                name: {
                    $regex: value,
                    $options: "$i"
                }
            }
        },

        {
            $skip: (currentPage - 1) * pageSize
        },

        {
            $limit: (pageSize - 0)
        }
    ])

    const total = await sellersModel.countDocuments({
        delete: false,
        name: {
            $regex: value,
            $options: "$i"
        }
    })
    const pages = Math.ceil(total / pageSize)
    return {
        total,
        pages,
        data
    }
}

module.exports.getSellersById = async function ({ _id }) {
    const data = await sellersModel.aggregate([
        {
            $lookup: {
                // 设置关联的集合名称
                from: "customers",
                // 当前集合中做关联的属性名（字段）
                localField: "_id",
                // 被关联集合对应的属性名
                foreignField: "salesmansId",
                as: "customers"
            },
        },
        {
            $match: {
                delete: false,
                _id: mongoose.Types.ObjectId(_id)
            }
        },

    ])

    return data
},

    // 获取全部订单
    module.exports.getSellersOrderById = async function getSellersOrderById({ _id, pageSize,
        currentPage, nameData, timeData }) {
        const customersId = (await customersModel.find({
            salesmansId: _id, name: {
                $regex: nameData,
                $options: "$i"
            }
        }, '_id')).map(item => item._id);

        const allOrders = await ordersModel.find({
            customersId: { $in: customersId }, 
            ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
            .populate({
                path: "insuresId",
                populate: {
                    path: "typesId",
                },
            })
            .populate('customersId')
            .limit(pageSize - 0).skip((currentPage - 1) * pageSize);


        const paidOrders = await ordersModel.find({
            customersId: { $in: customersId }, ordersPayState: 0, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
            .populate({
                path: "insuresId",
                populate: {
                    path: "typesId",
                },
            })
            .populate('customersId')
            .limit(pageSize - 0).skip((currentPage - 1) * pageSize);

        const payOffOrders = await ordersModel.find({
            customersId: { $in: customersId }, ordersPayState: 1, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        .populate({
            path: "insuresId",
            populate: {
                path: "typesId",
            },
        })
        .populate('customersId')
            .limit(pageSize - 0).skip((currentPage - 1) * pageSize);

        const toCancelOrders = await ordersModel.find({
            customersId: { $in: customersId }, ordersPayState: 4, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        .populate({
            path: "insuresId",
            populate: {
                path: "typesId",
            },
        })
        .populate('customersId')
            .limit(pageSize - 0).skip((currentPage - 1) * pageSize);



        const toCancelingOrders = await ordersModel.find({
            customersId: { $in: customersId }, ordersPayState: 2, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        .populate({
            path: "insuresId",
            populate: {
                path: "typesId",
            },
        })
        .populate('customersId')
            .limit(pageSize - 0).skip((currentPage - 1) * pageSize);

        const toCanceledOrders = await ordersModel.find({
            customersId: { $in: customersId }, ordersPayState: 3, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        .populate({
            path: "insuresId",
            populate: {
                path: "typesId",
            },
        })
        .populate('customersId')
            .limit(pageSize - 0).skip((currentPage - 1) * pageSize);

        const allTotal = await ordersModel.countDocuments({
            customersId: { $in: customersId }, delete: false, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        const paidTotal = await ordersModel.countDocuments({
            customersId: { $in: customersId }, delete: false, ordersPayState: 0, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        const payOffTotal = await ordersModel.countDocuments({
            customersId: { $in: customersId }, delete: false, ordersPayState: 1, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })

        const toCancelingTotal = await ordersModel.countDocuments({
            customersId: { $in: customersId }, delete: false, ordersPayState: 2, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        const toCanceledTotal = await ordersModel.countDocuments({
            customersId: { $in: customersId }, delete: false, ordersPayState: 3, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })

        const toCancelTotal = await ordersModel.countDocuments({
            customersId: { $in: customersId }, delete: false, ordersPayState: 4, ordersTime: {
                $regex: timeData,
                $options: "$i"
            }
        })
        console.log(toCancelOrders);
        return {
            allOrders,
            paidOrders,
            payOffOrders,
            toCancelingOrders,
            toCanceledOrders,
            toCancelOrders,
            allTotal,
            paidTotal,
            payOffTotal,
            toCancelingTotal,
            toCanceledTotal,
            toCancelTotal
        }
    }


// 获取客户
module.exports.getSellersUserById = async function getSellersUserById({ _id, value,
    currentPage, type, pageSize }) {
    const customersData = await customersModel.find({
        salesmansId: { $in: _id }, delete: false, [type]: {
            $regex: value,
            $options: "$i"
        }
    })
        .limit(pageSize - 0).skip((currentPage - 1) * pageSize);

    const total = await customersModel.countDocuments({
        salesmansId: _id, delete: false, [type]: {
            $regex: value,
            $options: "$i"
        }
    })
    return { customersData, total }
}

module.exports.getSellersByIdForClaims = async function getSellersByIdForClaims({ _id, pageSize,
    currentPage, value, type }) {
    const customersId = (await customersModel.find({ sellersId: _id }, '_id')).map(item => item._id);
    const ordersId = (await ordersModel.find({
        customersId: { $in: customersId },
        $or: [
            {
                ordersState: 1,
            }
            ,
            {
                ordersState: 2
            }
        ],
    })).map(item => item._id);
    const orders = await ordersModel.find({ customersId: { $in: customersId }, ordersState: 1 })
        .populate({
            path: "insuresId",
            populate: {
                path: "typesId",
            },
        })
        .populate({
            path: "customersId",
            populate: {
                path: "salesmansId",
            }
        })

    const allClaims = await claimsModel.find({
        ordersId: { $in: ordersId },
        $or: [
            {
                state: 1,
            }
            ,
            {
                state: 2
            }
        ],
        [type]: {
            $regex: value,
            $options: "$i"
        }
    })
        .populate({
            path: "ordersId",
            populate: {
                path: "insuresId",
                populate: {
                    path: "typesId",
                },

            },
        })
        .populate({
            path: "ordersId",
            populate: {
                path: "customersId",
                populate: {
                    path: "salesmansId",
                },
            }
        })
        .limit(pageSize - 0).skip((currentPage - 1) * pageSize);

    const total = await claimsModel.countDocuments({
        ordersId: { $in: ordersId },
        $or: [
            {
                state: 1,
            }
            ,
            {
                state: 2
            }
        ],
        delete: false,
        [type]: {
            $regex: value,
            $options: "$i"
        }
    })
    return { allClaims, total, orders }
}

module.exports.changeSellersById = async function changeSellersById(params) {
    return await sellersModel.updateOne({
        _id: params._id
    }, {
        ...params
    })
}

module.exports.delSellersById = async function (params) {
    return await sellersModel.updateOne({
        _id: params
    }, {
        delete: true,
    })
}




